package com.bjpowernode.seckillweb.service.impl;

import com.bjpowernode.constant.Constants;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 将lua脚本交给redis执行
 */
@Component
public class LuaService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    //泛型表示lua脚本的返回值
    private DefaultRedisScript<Long> redisScript;


    /**
     * 在当前bean对象创建之后执行的操作
     */
    @PostConstruct
    public void init() {
        redisScript = new DefaultRedisScript<>();
        //设置返回值类型
        redisScript.setResultType(Long.class);

        //读取的lua脚本
        redisScript.setScriptSource(
                new ResourceScriptSource(
                        new ClassPathResource("seckill.lua")));
    }


    public Long runLua(Integer goodsId, Integer userId) {
        //限流的key  单位精确到秒
        String limitKey = System.currentTimeMillis() / 1000 + "";

        //表示用户是否秒杀过该商品
        String holdKey = Constants.REDIS_HOLD + goodsId + ":" + userId;

        //商品库存key
        String storeKey = Constants.REDIS_STORE + goodsId;

        //将key放入list中
        List<String> keyList = Arrays.asList(limitKey, holdKey, storeKey);

        //执行lua脚本并传入参数,并获取lua的返回结果
        Long executeResult = stringRedisTemplate.execute(redisScript, keyList, String.valueOf(userId), String.valueOf(Constants.MAX_LIMIT));


        return executeResult;
    }
}
